package com.itheima.reggie.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.dao.CategoryDao;
import com.itheima.reggie.dao.DishDao;
import com.itheima.reggie.dao.SetmealDao;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.exception.CustomerException;
import com.itheima.reggie.service.CategoryService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired(required = false)
    private CategoryDao categoryDao;
    @Autowired(required = false)
    private DishDao dishDao;
    @Autowired(required = false)
    private SetmealDao setmealDao;
    /**
     * 添加菜品类型
     */
    @Override
    public void save(Category category) {
//        补全时间信息
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
//        添加输数据
        categoryDao.save(category);

    }

    @Override
    public Page<Category> findAll(Integer page,Integer pageSize) {
//        获取起始页和页面大小
        PageHelper.startPage(page,pageSize);
//        获取所有信息
        List<Category> categories = categoryDao.findAll();
//        获取pageinfo信息
        PageInfo<Category>categoryList=new PageInfo<>(categories);
        Page<Category>pageList=new Page<>();
        pageList.setPageSize(categoryList.getPageSize());
        pageList.setPage(categoryList.getPageNum());
        pageList.setTotal(categoryList.getTotal());
        pageList.setRecords(categoryList.getList());
        return pageList;
    }
    /**
     * 删除菜品
     * http://localhost:8080/category?id=1397844303408574465
     */
    @Override
    public void deleteCate(Long id) {
//        判断所删除的套餐是否有关联
//        1.先查询关联的数量，小于0直接删除，大于0提示不能删除
        Integer countByCategoryId = dishDao.findCountByCategoryId(id);
        Integer countByCategoryId1 = setmealDao.findCountByCategoryId(id);


        if (countByCategoryId>0){
            throw new CustomerException("该类别已经关联套餐不能直接删除");
        }
        if (countByCategoryId1>0){
            throw new CustomerException("该类别已经关联套餐不能直接删除");
        }
        categoryDao.findById(id);
    }
    /**
     * 修改数据
     * RL: http://localhost:8080/category
     * put
     */
    @Override
    public void update(Category category) {
        categoryDao.update(category);
    }
/*
查询所有
 */
    @Override
    public List<Category>findAllmsg() {
        return  categoryDao.findAll();
    }
    /**
     * 获取菜品分类
     * http://localhost:8080/category/list?type=1
     * get
     */
    @Override
    public List<Category> findByType(Integer type) {
       return categoryDao.findByType(type);

    }



}
